package cn.jiedanba.cacert.admin.service.impl;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mybatisflex.core.query.QueryWrapper;

import cn.jiedanba.cacert.admin.service.SysUserService;
import cn.jiedanba.cacert.admin.vo.LoginVo;
import cn.jiedanba.cacert.common.result.ResponseResult;
import cn.jiedanba.cacert.common.util.ServletUtils;
import cn.jiedanba.cacert.mapper.SysUserMapper;
import cn.jiedanba.cacert.model.SysUser;
import cn.jiedanba.cacert.table.Tables;

@Service
public class SysUserServiceImpl implements SysUserService {

	@Autowired
	private SysUserMapper sysUserMapper;

	/**
	 * 登录
	 * 
	 * @param login
	 * @return
	 */
	@Override
	public ResponseResult login(LoginVo login, HttpServletRequest request) {
		QueryWrapper wrapper = QueryWrapper.create();

		wrapper.and(Tables.SYS_USER.LOGIN_NAME.eq(login.getLoginName())).from(Tables.SYS_USER);
		SysUser user = sysUserMapper.selectOneByQuery(wrapper);
		if (user == null) {
			return ResponseResult.fail("账号不存在");
		}

		String password = DigestUtils.sha256Hex(user.getId() + DigestUtils.sha256Hex(login.getPassword()));
		if (!user.getPassword().equals(password)) {
			return ResponseResult.fail("登录名或密码错误");
		}

		ServletUtils.getSession().setAttribute("sysUser", user);
		return ResponseResult.success();
	}

}
